package cn.tedu.order.service;

import cn.tedu.order.entity.AccountMessage;
import cn.tedu.order.entity.Order;
import cn.tedu.order.entity.TxInfo;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @ClassName OrderServiceImpl
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/7/1 11:47
 * @Version V1.0
 **/
@Service
@RocketMQTransactionListener
@Slf4j
public class OrderServiceImpl implements OrderService, RocketMQLocalTransactionListener {
    @Autowired
    EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private TxMapper txMapper;

    //业务方法中,不直接执行业务处理
    //而是发送事务消息,半消息
    @Override
    public void create(Order order) {

        //UUID产生xid事务id
        String xid = UUID.randomUUID().toString().replace("-", "");
//        AccountMessage封装数据-转成json-json封装到spring的通用message
        AccountMessage am = new AccountMessage(order.getUserId(),order.getMoney(),xid);
        String json = JsonUtil.to(am);
        Message<String> msg = MessageBuilder.withPayload(json).build();

        //如果有标签,格式:    orderTopic:tag1
        rocketMQTemplate.sendMessageInTransaction(
                "orderTopic",msg,order);

    }

//完成业务处理的方法
    public void docreate(Order order) {
        //生成订单id
        String s= easyIdClient.nextId("order_business");
        //包装类Long
        Long orderId = Long.valueOf(s);

        order.setId(orderId);
        orderMapper.create(order);

        //远程调用账户扣减账户金额
//accountClient.decrease(order.getUserId(), order.getMoney());

        //远程调用库存减少商品库存
//storageClient.decrease(order.getProductId(), order.getCount());

    }
    //执行本地事务
    @Transactional
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(
            Message message, Object o) {
        //存储到数据表的状态值用0和1表示成功和失败
        int status;
        //返回的事务状态是一个State对象
        RocketMQLocalTransactionState state;

        try {
            Order order = (Order) o;
            System.out.println("执行本地事务");
            //执行原来的业务代码
            docreate(order);
            //Thread.sleep(70*1000);
            System.out.println("本地事务执行成功");
            status=0;
            state=RocketMQLocalTransactionState.COMMIT;

        }catch (Exception e){
            log.error("本地事务存储订单失败", e);
            status=1;
            state=RocketMQLocalTransactionState.ROLLBACK;
        }
            //把事务状态存到数据表的 tx_table
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        txMapper.insert(new TxInfo(xid, System.currentTimeMillis(), status));
        return state;
    }
    //处理事务状态回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        System.out.println("正在处理RocketMQ服务器的事务状态回查");
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        TxInfo txInfo = txMapper.selectById(xid);
        if (txInfo==null){
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        switch (txInfo.getStatus()){
            case 0:return RocketMQLocalTransactionState.COMMIT;
            case 1:return RocketMQLocalTransactionState.ROLLBACK;
            default:return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
